<?php

/**
 * Created by PhpStorm.
 * User: allen_ios
 * Date: 17/6/12
 * Time: 下午6:47
 */
class ZduRestaurantAction extends BaseAction
{
    public $resId; // 模块id
    public $restaurantId;
    public $sRestaurant;

    public function _initialize()
    {
        parent::_initialize();
        $action = array('index');
        if (in_array(strtolower(ACTION_NAME), $action)) {
            // 获取模块id
            $this->resId = $this->_request('res_id');
            // 获取餐厅id
            $this->restaurantId = $this->_request('id');

            if (!$this->resId) {
                exit('模块参数丢失!');
            }

            if (!$this->restaurantId ){
                exit('参数错误!');
            }

            $this->assign('restaurant_id', $this->restaurantId );

            $this->assign('res_id',$this->resId);
        }
    }

    /**
     * 获取菜品分类信息
     */
    public function index()
    {
        //获取菜品分类,调用service
        // 实例化服务类Service();第一个参数是文件路径:'ZdRestaurant/ZdRestaurant'
        $this->sRestaurant = Service('BaseRestaurant','',array($this->resId,$this->restaurantId));
        // 查询改餐厅下所有的分类
        $allCategory = $this->sRestaurant->getCategory();

        $this->assign('allCategory',$allCategory);

        $this->display();
    }


    /**
     * 根据category_id获取分类下的菜品信息
     */
    public function ajaxGetCategoryGoods(){

        $category_id = $this->_request("category_id");
        
        $restaurant_id = $this->_request("restaurant_id");

        $res_id = $this->_request("res_id");
        
        if (!$restaurant_id||!$res_id){
            $this->ajaxReturn(array('status' => 'F','message' => '参数错误'.$restaurant_id.$res_id));
        }
        
        $sGoods = Service('BaseGoods');
        // 获取热门菜品-12份
        if ($category_id==0){
            $list = $sGoods->getHotGoods($restaurant_id);
        }else{
            $list = $sGoods->getGoods($category_id,$res_id);
        }
        
        if (!$list){
            $this->ajaxReturn(array('status' => 'F','message' => '没有菜品'));
        }
        $sCart = Service('BaseCart','',array($restaurant_id));

        foreach ($list as $key=>$value){
            $list[$key]['cart_num'] = $sCart->getCartGoodsNum($value['goods_id']);
        }

        $sCart = Service('BaseCart','',array($restaurant_id));
        $cartList = $sCart->getRestaurantCartList();
        $sum = 0;
        $num= 0;
        foreach ($cartList as $key=>$value){
            $goodsInfo = $sGoods->getGoodsInfo($value['goods_id']);
            $cartList[$key]['sum_price'] = sprintf ("%01.2f", $value['cart_num'] * $goodsInfo['price']);
            $sum+= $value['cart_num'] * $goodsInfo['price'];
            $num+=$value['cart_num'];
        }
        $sum = sprintf ("%01.2f",$sum);
        if (!$sum){
            $sum = '0.00';
        }

        $this->ajaxReturn(array('status' => 'S','message' => '请求成功','data'=>$list,'all_number'=>$num,'all_price'=>$sum));

    }


    /**
     * 购物车列表
     */
    public function ajaxListCart()
    {
        $restaurant_id = $this->_request("restaurant_id");

        if (!$restaurant_id){
            $this->ajaxReturn(array('status' => 'F','message' => '参数错误'));
        }

        $sCart = Service('BaseCart','',array($restaurant_id));
        $sGoods = Service('BaseGoods');
        $cartList = $sCart->getRestaurantCartList();
        if (!$cartList){
            $this->ajaxReturn(array('status' => 'F','message' => '购物车为空'));
        }
        $sum = 0;
        $num= 0;
        foreach ($cartList as $key=>$value){
            $goodsInfo = $sGoods->getGoodsInfo($value['goods_id']);
            $cartList[$key]['price'] = $goodsInfo['price'];
            $cartList[$key]['sum_price'] =  sprintf ("%01.2f",$value['cart_num'] * $goodsInfo['price']);
            $sum+= $value['cart_num'] * $goodsInfo['price'];
            $num+=$value['cart_num'];
        }
        $sum = sprintf ("%01.2f",$sum);
        if (!$sum){
            $sum = '0.00';
        }

        $this->ajaxReturn(array('status' => 'S','message' => '请求成功','all_number'=>$num,'all_price'=>$sum,'data'=>$cartList));
    }

    /**
     * 更新购物车操作
     */
    public function ajaxUpdateCart(){

        $restaurant_id = $this->_request("restaurant_id");

        //菜品id
        $goods_id = $this->_request("goods_id");
        //菜品数量
        $goods_num = $this->_request("goods_num");
        //操作类型 1:点击+或点击菜品(新增或增加数量),2:点击-(减少菜品数量),3:输入一个数字,更新购物车(+-之间的输入框出发的方法)
        $type = $this->_request('type');


        if (!$restaurant_id||!$goods_id){
            $this->ajaxReturn(array('status' => 'F','message' => '参数错误'));
        }
        if (!in_array($type,array(1,2,3))){
            $this->ajaxReturn(array('status' => 'F','message' => '参数错误'));
        }

        $sCart = Service('BaseCart','',array($restaurant_id));

        $sGoods = Service('BaseGoods');

        // 获取商品信息
        $goodsInfo = $sGoods->getGoodsInfo($goods_id);

        if ($type==1){
            // 检查库存
            $sGoods = Service('BaseGoods');
            $goodsInfo =  $sGoods->checkStorage($goods_id,$goods_num);
            if (!$goodsInfo){
                $this->ajaxReturn(array('status' => 'F','message' => '库存不足'));
            }
            $sCart = Service('BaseCart','',array($restaurant_id));

            // 返回的是操作后的数量
            $num = $sCart->doCart($goods_id,$goodsInfo['goods_name'],$goods_num,0);
            if (!$num){
                $this->ajaxReturn(array('status' => 'F','message' => '添加失败'));
            }else{

                $this->ajaxReturn(array('status' => 'S','message' => '添加成功'));
            }
        }elseif ($type==2){

            // 减购物车商品
            $num = $sCart->doCart($goods_id,$goodsInfo['goods_name'],$goods_num,1);


            if ($num==0){
                $res = $sCart->deleteCart($goods_id);
            }

            $this->ajaxReturn(array('status' => 'S','message' => '删除成功'));
        }else{
            if (!$goods_num){// 将菜品数量置为0,表示删除这个购物车

                // 删除购物车内容
                $res = $sCart->deleteCart($goods_id);
                if ($res){
                    $this->ajaxReturn(array('status' => 'S','message' => '删除成功'));
                }else{
                    $this->ajaxReturn(array('status' => 'F','message' => '更新失败'));
                }

            }else{

                $data = array(
                    'goods_id'=>$goods_id,
                    'goods_name'=>$goodsInfo['goods_name'],
                    'cart_num'=>$goods_num
                );
                // 更新购物车
                $res = $sCart->updateCart($goods_id,$data);
                if ($res){
                    $this->ajaxReturn(array('status' => 'S','message' => '删除成功'));
                }else{
                    $this->ajaxReturn(array('status' => 'F','message' => '更新失败'));
                }
            }
        }
    }

    /**
     * 订单提交，生成支付宝二维码
     */
    public function ajaxAddOrder()
    {
        // 结算购物车
        $restaurant_id = $this->_request("restaurant_id");
        $res_id = $this->_request("res_id");


        if (!$restaurant_id||!$res_id){
            $this->ajaxReturn(array('status' => 'F','message' => '参数错误'));
        }

        
        $sCart = Service('BaseCart','',array($restaurant_id));
        $sGoods = Service('BaseGoods');
        $sOrder = Service('BaseOrder');
        $cartList = $sCart->getRestaurantCartList();
        if (!$cartList){
            $this->ajaxReturn(array('status' => 'F','message' => '购物车为空,请选择菜品'));
        }
        //生成订单号
        $orderSn = $this->getOrderSn('zduRestaurant');
        //生成订单
        $data = array();
        $data['order_sn'] = $orderSn['data']; 
        $data['status'] = 0;
        $data['user_id'] = 0;
        $data['res_id'] = $res_id;
        $data['restaurant_id'] = $restaurant_id;
        $data['create_time'] = time();
        $data['is_pay_notify'] = 0;
        $data['pay_type'] = 2;
        //往订单表插入数据

        $ret = $sOrder->addOrder($data);

        if (!$ret){
            $this->ajaxReturn(array('status' => 'F','message' => '生成订单失败'));
        }

        $sum = 0;
        foreach ($cartList as $key=>$value){
            $goodsInfo = $sGoods->getGoodsInfo($value['goods_id']);
            $cartList[$key]['sum_price'] = $value['cart_num'] * $goodsInfo['price'];
            $sum+= $value['cart_num'] * $goodsInfo['price'];
            $orderGoodsInfo[] = array(
                'order_id' => $ret,
                'goods_id' => $value['goods_id'],
                'restaurant_id' => $restaurant_id,
                'goods_num' => $value['cart_num'],
                'create_time' => time(),
                'user_id' => 0,
                'goods_name' => $goodsInfo['goods_name'],
                'goods_price' => $goodsInfo['price'],
                'goods_logo' => $goodsInfo['goods_logo'],
            );
        }
        $res = $sOrder->addGoodsAll($orderGoodsInfo);

        if (!$res){
            $this->ajaxReturn(array('status' => 'F','message' => '插入订单物品失败'));
        }
        // 更新订单 order_amount
        $data = array(
            'order_amount'=>$sum
        );
        $updateOrder = $sOrder->updateOrder($ret,$data);

        if (!$updateOrder){
            $this->ajaxReturn(array('status' => 'F','message' => '出错了'));
        }

        // 清空购物车
        $sCart->emptyRestaurantCardList();


        $array =array(
            'order_id'=>$ret,
            'order_sn'=>$orderSn['data'],
            'order_amount'=> sprintf ("%01.2f",$sum)
        );

        $this->ajaxReturn(array('status' => 'S','message' => '生成订单成功','data'=>$array));

    }

    /**
     * 针对现金支付
     */
    public function offlinePayOrder(){

        $order_id = $this->_request("order_id");

        if (!$order_id){
            $this->ajaxReturn(array('status' => 'F','message' => '参数错误'));
        }
        $sOrder = Service('Restaurant/BaseOrder');

        $update = array(
            'status' => 1,
            'pay_type' => 9,
            'pay_time' => time(),
        );
        $res = $sOrder->updateOrder($order_id,$update);

        if (!$res){
            $this->ajaxReturn(array('status' => 'F','message' => '订单打印失败'));
        }
        $sGoods = Service('Restaurant/BaseGoods');
        // 减库存,加销量
        $sGoods->changeGoodsNum($order_id);
        // 打印小票
        $this->useWifiPrintInfo($order_id);

        $this->ajaxReturn(array('status' => 'S','message' => '订单打印成功'));
    }


    /**
     * 清空购物车接口
     */
    public function emptyRestaurantCart(){


        $restaurant_id = $this->_request("restaurant_id");

        if (!$restaurant_id){
            $this->ajaxReturn(array('status' => 'F','message' => '参数错误'));
        }
        $sCart = Service('BaseCart','',array($restaurant_id));

        $res = $sCart->emptyRestaurantCardList();

        if (!$res){
            $this->ajaxReturn(array('status' => 'F','message' => '清空购物车失败'));
        }
        $this->ajaxReturn(array('status' => 'S','message' => '清空购物车成功'));
    }


    /**
     * 生成二维码
     */
    public function qrcode()
    {
        $qr_code_message = $this->_get('qr_code');

        if (!$qr_code_message) {
           exit;
        }
        vendor('phpqrcode.phpqrcode');
        $errorCorrectionLevel = 'L';//容错级别
        $matrixPointSize = 12;//生成图片大小
        //生成二维码图片
        QRcode::png(base64_decode($qr_code_message), false, $errorCorrectionLevel, $matrixPointSize, 2, true);
    }


    /**
     * 去支付
     */
    public function gotoPay()
    {

        $this->display();
    }


    /**
     * 查询购物车状态
     */
    public function checkOrderStatus(){
        
        $order_id = $this->_request("order_id");

        if (!$order_id){
            $this->ajaxReturn(array('status' => 'F','message' => '参数错误'));
        }
        $sOrder = Service('BaseOrder');
        // 查询订单状态
        $orderInfo  = $sOrder->getOrderInfo($order_id);
        if ($orderInfo['status']==0){
            $this->ajaxReturn(array('status' => 'F','message' => '未支付'));
        } elseif($orderInfo['status']==1){
            $this->ajaxReturn(array('status' => 'S','message' => '支付成功'));
        }else{
            $this->ajaxReturn(array('status' => 'F','message' => '订单已关闭'));
        }
    }

    /**
     * 取消订单
     */
    public function cancelOrder(){

        $order_id = $this->_request("order_id");

        if (!$order_id){
            $this->ajaxReturn(array('status' => 'F','message' => '参数错误'));
        }
        $sOrder = Service('BaseOrder');

        // 获取订单信息
        $orderInfo = $sOrder->getOrderInfo($order_id,'order_sn,restaurant_id,status');

        if (!$orderInfo){
            $this->ajaxReturn(array('status' => 'F','message' => '获取订单失败'));
        }
        if ($orderInfo['status']!=0){
            $this->ajaxReturn(array('status' => 'F','message' => '订单已完成或已取消'));
        }
        $data = array('status'=>8);

        $res = $sOrder->updateOrder($order_id,$data);
        if (!$res){
            $this->ajaxReturn(array('status' => 'F','message' => '订单取消失败'));
        }
        $this->ajaxReturn(array('status' => 'S','message' => '订单取消成功'));
    }

    /**
     * 支付回调
     */
    public function notify($orderId){

        if (!$orderId){
            exit('fail');
        }
        $sGoods = Service('Restaurant/BaseGoods');
        $sOrder = Service('Restaurant/BaseOrder');
        // 减库存,加销量
        $sGoods->changeGoodsNum($orderId);
        // 打印小票
        $this->useWifiPrintInfo($orderId);

        exit('success');
    }


    public function closeNotify(){

    }
    /**
     * 打印订单
     * @param $orderId
     */
    function useWifiPrintInfo($orderId){

        $mOrder = D('Base/RestaurantOrder');
        $mGoods = D('Base/RestaurantGoods');
        $mOrderGoods= D('Base/RestaurantOrderGoods');
        $mWindow = D('Base/RestaurantWindow');
        //查询订单信息
        $info = $mOrder->relation(true)->getByPk($orderId);

        if($info){

            $windowInfo = array();

            $windowIdArray = $mWindow->where(array('restaurant_id'=>$info['restaurant_id'],'cut_off'=>0))->getField('window_id',true);

            foreach($windowIdArray as $window_id){
                //查询菜品对应的种类对应档口及打印机信息

                $wInfo = $mWindow->getByPk($window_id);
                //$wInfo = $this->mWindow->getInfo($list['window_id']);
                $windowInfo[$wInfo['window_id']]['window_id'] = $wInfo['window_id'];
                $windowInfo[$wInfo['window_id']]['print_key'] = $wInfo['print_key'];
                $windowInfo[$wInfo['window_id']]['print_dno'] = $wInfo['print_dno'];
                $windowInfo[$wInfo['window_id']]['print_username'] = $wInfo['print_username'];
                $windowInfo[$wInfo['window_id']]['print_count'] = $wInfo['print_count'];

            }

            if($windowInfo){
                // 获取订单商品id
                $orderGoodsArray = $mOrderGoods->field('goods_id,goods_num,goods_price,goods_name')->where(array('order_id'=>$orderId))->select();

                $headerStr = '';

                $content = $headerStr.
                    '|5================================'.'\r\n'.
                    '餐厅名：'.$info['RestaurantInfo']['restaurant_name'].'\r\n'.
                    '订单号：'.$info['order_sn'].'\r\n'.
                    '总计：'.$info['order_amount'].'\r\n'.
                    '菜单信息：\r\n';
                foreach ($orderGoodsArray as $key=>$value){

                    $price= $value['goods_price']*$value['goods_num'];

                    $content = $content.
                        $value['goods_name'].'  × '.$value['goods_num'].'  '.$value['goods_price']*$value['goods_num'].'\r\n';
                }
                $content =$content.
                    '欢迎下次惠顾 ! \r\n';

                foreach($windowInfo as $val){

                    $str = $val['print_key'].$val['print_dno'].'aykj';
                    $keyInfo = md5($str);
                    $username = $val['print_username'];
                    $dno = $val['print_dno'];
                    $times = $val['print_count'];
                    $this->useWifiPrint($times,$keyInfo,$content, $username, $dno);
                }
            }
        }
    }

    /**
     *使用wifi打印机打印
     * @param int $times 打印次数
     * @param string $key 加密字符串
     * @param string $content 打印内容
     * @param string $username 官网用户名
     * @param string $dno 设备编号
     * @param int $mode 打印模式（0 混合打印;1文本打印; 2二维码打印;3条码打印）
     * @param string $msgno 订单编号（不传则自动生成）
     * @param string $op 操作类型（pf:打印操作  cx：查询打印机状态 cxdd：查询订单状态）
     * @param string $qr 支付宝二维码图片链接地址（可选）
     * @return array
     */
    function useWifiPrint($times = 1,$key, $content, $username, $dno, $mode = 0, $msgno = '', $op = 'pf', $qr = '')
    {
        /**
        返回状态码
        0 成功
        1 订单发送失败';
        200 查询失败';
        201 不存在当前设备';
        300 二维码打印成功';
        301 二维码打印失败';
        401 查询订单失败';
        900 没有相关操作';
        901 操作错误';
        -2 验证错误';
        -3 绑定设备不属于该用户';
        -4 打印类型错误';
        -5 该用户无效';
        -7 设备号';
        -8 参数错误';
        -102 条形码打印存在汉字';
        -103 组合打印类型不含有前缀';
         * */
        $result = array();
        for($i = 0; $i < $times; $i ++) {
            $url = 'http://121.43.235.40/WS/DealData.ashx';
            $fields = array(
                'op' => $op,
                'content' => $content.
                    '序号：'.($i+1).'\r\n'.
                    '================================'.'\r\n'.
                    '|4技术支持：杭州青橄榄网络技术有限公司',
                'key' => $key,
                'unm' => $username,
                'dno' => $dno,
                'mode' => '|' . $mode,
                'msgno' => $msgno,
                'qr' => $qr,
            );

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, count($fields)); // 启用时会发送一个常规的POST请求，类型为：application/x-www-form-urlencoded，就像表单提交的一样。
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); // 在HTTP中的“POST”操作。如果要传送一个文件，需要一个@开头的文件名

            ob_start();
            curl_exec($ch);

            $result[] = ob_get_contents();
            ob_end_clean();
        }
        return $result;
    }
}